package com.clz.latte.ec.main.Index;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clz.latte.delegate.bottom.BottomItemDelegate;
import com.clz.latte.ec.R;
import com.clz.latte.ec.R2;
import com.clz.latte.ec.entity.IndexBean;
import com.clz.latte.ec.main.EcBottomDelegate;
import com.clz.latte.ec.main.Index.adapter.IndexAdapter;
import com.clz.latte.net.RestClient;
import com.clz.latte.net.callback.IRequest;
import com.clz.latte.net.callback.ISuccess;
import com.clz.latte.ui.recycler.BaseDecoration;
import com.clz.latte.ui.recycler.RgbValue;
import com.clz.latte.ui.refresh.RefreshHandler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.joanzapata.iconify.widget.IconTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/3/20.
 * 首页
 */

public class IndexDelegate extends BottomItemDelegate {
    @BindView(R2.id.refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R2.id.rel_goods)
    RecyclerView mRclGoods;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.icon_index_scan)
    IconTextView mIconScan;
    @BindView(R2.id.et_search_view)
    AppCompatEditText mSearchView;
    @BindView(R2.id.icon_index_message)
    IconTextView mIconMessage;
    private RefreshHandler mRefreshHandler = null;
    private IndexAdapter mAdapter;
    private List<IndexBean> data = new ArrayList<>();

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mRefreshHandler = new RefreshHandler(mRefresh);
        initRecAdapter();
        getIndexData(true);
    }

    //定义变化的颜色
    private static final RgbValue RGB_VALUE = RgbValue.create(255, 124, 2);

    private void initRecAdapter() {
        mRclGoods.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mAdapter = new IndexAdapter(data);
        mRclGoods.setAdapter(mAdapter);
        mRefresh.setRefreshing(true);
        mRclGoods.addItemDecoration(BaseDecoration.create(ContextCompat.getColor(getContext(), R.color.app_background), 5));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mRefresh.setRefreshing(false);
                mAdapter.setEnableLoadMore(true);
                getIndexData(false);
            }
        }, mRclGoods);
        EcBottomDelegate ecBottomDelegate= getParentDaleGate();
        mRclGoods.addOnItemTouchListener(IndexItemOnclickListener.create(ecBottomDelegate));
        scrollRclGoods();
    }

    /**
     * 监测recyclerView滚动距离
     */
    private void scrollRclGoods() {
        mRclGoods.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int dy2;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, final int dx, final int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int scrollHeight = mRclGoods.computeVerticalScrollOffset();
                final int height = mRclGoods.getChildAt(0).getMeasuredHeight() - mToolbar.getMeasuredHeight();
                LogUtils.d(height + "," + scrollHeight);
                if (scrollHeight <= height) {
                    final float scale = (float) scrollHeight / height;
                    final float alpha = scale * 255;
                    mToolbar.setBackgroundColor(Color.argb((int) alpha, RGB_VALUE.red(), RGB_VALUE.green(), RGB_VALUE.blue()));
                } else {
                    mToolbar.setBackgroundColor(Color.rgb(RGB_VALUE.red(), RGB_VALUE.green(), RGB_VALUE.blue()));
                }
//                mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
//                    @Override
//                    public void onItemRangeInserted(int positionStart, int itemCount) {
//                        super.onItemRangeInserted(positionStart, itemCount);
//                        dy2 += dy;
//                    }
//
//
//                    @Override
//                    public void onItemRangeRemoved(int positionStart, int itemCount) {
//                        super.onItemRangeRemoved(positionStart, itemCount);
//                        dy2 -= dy;
//                    }
//
//                    @Override
//                    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
//                        super.onItemRangeMoved(fromPosition, toPosition, itemCount);
//                    }
//                });
//                LogUtils.d(dy2 + "," + height);
//                if (dy2 <= height) {
//                    final float scale = (float) dy2 / height;
//                    final float alpha = scale * 255;
//                    mToolbar.setBackgroundColor(Color.argb((int) alpha, RGB_VALUE.red(), RGB_VALUE.green(), RGB_VALUE.blue()));
//                } else {
//                    mToolbar.setBackgroundColor(Color.rgb(RGB_VALUE.red(), RGB_VALUE.green(), RGB_VALUE.blue()));
//                }
            }
        });
    }

    private void getIndexData(final boolean isRefresh) {
        RestClient.builder()
                .url("index.php")
                .sucess(new ISuccess() {
                    @Override
                    public void onSucess(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        final JSONArray json = jsonObject.getJSONArray("data");
                        Gson gson = new Gson();
                        List<IndexBean> beans = gson.fromJson(json.toJSONString(), new TypeToken<ArrayList<IndexBean>>() {
                        }.getType());
                        if (isRefresh) {
                            mAdapter.setNewData(beans);
                        } else {
                            beans.remove(0);
                            mAdapter.addData(beans);
                        }
                    }
                })
                .onRequest(new IRequest() {
                    @Override
                    public void onRequestStart() {

                    }

                    @Override
                    public void onRequestEnd() {
                        mRefresh.setRefreshing(false);
                        mAdapter.loadMoreComplete();
                    }
                })
                .build()
                .get();
    }

    private void initRefreshLayout() {
        mRefresh.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light

        );
        mRefresh.setProgressViewOffset(true, 120, 300);
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAdapter.setEnableLoadMore(false);
                mRefresh.setRefreshing(true);
                getIndexData(true);
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initRefreshLayout();
        // mRefreshHandler.firstPage("index.php");
    }

    @Override
    public Object setLayOut() {
        return R.layout.delegate_index;
    }

}
